import React, { Component } from 'react'
import { Text, StyleSheet, View, ScrollView, TouchableOpacity, Image, TextInput, StatusBar, Alert, ImageBackground } from 'react-native'
import Ionicons from 'react-native-vector-icons/Ionicons'
import * as Animatable from 'react-native-animatable';
import LinearGradient from 'react-native-linear-gradient';
import { connect } from 'react-redux'
import { login } from '../../redux/actions/user'
import storage from '../../utils/storage'
import Users from '../../utils/users'

// import { useTheme } from 'react-native-paper';
// const { colors } = useTheme();


const mapStateToProps = state => ({
  isLoading: state.User.isLoading,
  isLogin: state.User.isLogin
})

class SignIn extends Component {
  constructor(props) {
    super(props)
    console.log('signin', this.props)
    this.state = {
      username: '',
      password: '',
      validateUsername: false,
      secureTextEntry: true,
      isValidUser: true,
      isValidPassword: true,
    }
  }

  validateUsername = (val) => {
    if ( val.trim().length >= 4 ) {
      this.setState({
        username: val,
        validateUsername: true,
        isValidUser: true
      });
    } else {
      this.setState({
        username: val,
        validateUsername: false,
        isValidUser: false
      });
    }
  }

  validatePassword = (val) => {
    if( val.trim().length >= 8 ) {
      this.setState({
        password: val,
        isValidPassword: true
      });
    } else {
      this.setState({
        password: val,
        isValidPassword: false
      });
    }
  }

  updateSecureTextEntry = () => {
    this.setState({
      secureTextEntry: !this.state.secureTextEntry
    });
  }

  handleValidUser = (val) => {
    if( val.trim().length >= 2 ) {
      this.setState({
        isValidUser: true
      });
    } else {
      this.setState({
        isValidUser: false
      });
    }
  }

  handleLogin = () => {
    const foundUser = Users.filter( item => {
      return this.state.username == item.username && this.state.password == item.password;
    } );

    if ( this.state.username.length == 0 || this.state.password.length == 0 ) {
      Alert.alert('输入错误!', '用户名和密码不能为空.', [
        {text: '确定'}
      ]);
      return;
    }

    if ( foundUser.length == 0 ) {
      Alert.alert('无效用户!', '用户名或密码无效.', [
        {text: '确定'}
      ]);
      return;
    }
    
    // 将登录返回的数据，存储下来
    let userInfo = {
      username: this.state.username,
      password: this.state.password
    }

    this.props.login(userInfo)
    storage.set('userInfo', userInfo)
  }

  render() {
    return (
      <View style={[styles.container]}>
        <ImageBackground source={require('../../images/bg2.jpeg')} style={styles.image}>
          <StatusBar hidden={true} />
          <View style={styles.header}>
            <Text style={styles.textHeader}>Welcome!</Text>
          </View>
          <Animatable.View animation="fadeInUpBig"
            style={[styles.footer, {
              backgroundColor: '#dfb'
            }]}
          >
            <ScrollView>
              <View style={styles.action}>
                <Ionicons name={'person-outline'} size={20} />
                <TextInput 
                  placeholder="用户名"
                  placeholderTextColor="#666666"
                  style={[styles.textInput]}
                  autoCapitalize="none"
                  onChangeText={(val) => this.validateUsername(val)}
                  onEndEditing={(e)=> this.handleValidUser(e.nativeEvent.text)}
                />
                {this.state.validateUsername ? 
                <Animatable.View animation="bounceIn" >
                  <Ionicons name={'checkmark-circle-outline'} size={20} />
                </Animatable.View>
                : null}
              </View>
              { 
              this.state.isValidUser ? null : 
              <Animatable.View animation="fadeInLeft" duration={500}>
              <Text style={styles.errorMsg}>用户名最短 2 位.</Text>
              </Animatable.View>
              }

              {/* <Text style={[styles.textFooter, styles.textColor, {
                    marginTop: 35
                }]}>密码</Text> */}
              <View style={styles.action}>
              <Ionicons name={'lock-closed-outline'} size={20} />
                <TextInput 
                  placeholder="密码"
                  placeholderTextColor="#666666"
                  secureTextEntry={this.state.secureTextEntry ? true : false}
                  style={[styles.textInput]}
                  autoCapitalize="none"
                  onChangeText={(val) => this.validatePassword(val)}
                />
                <TouchableOpacity onPress={this.updateSecureTextEntry} >
                  {this.state.secureTextEntry ? 
                  <Ionicons name={'eye-off-outline'} size={20} />
                  :
                  <Ionicons name={'eye-outline'} size={20} />
                  }
                </TouchableOpacity>
              </View>
              { this.state.isValidPassword ? null : 
              <Animatable.View animation="fadeInLeft" duration={500}>
              <Text style={styles.errorMsg}>密码最短 8 位.</Text>
              </Animatable.View>
              }

              <TouchableOpacity onPress={() => {
                Alert.alert('忘记密码!', '时间来不及，暂时没做.', [
                  {text: '确定'}
                ]);
              }} >
                <Text style={{color: '#009387', marginTop:15}}>忘记密码?</Text>
              </TouchableOpacity>
              <View style={styles.button}>
                <TouchableOpacity
                  style={styles.signIn}
                  onPress={() => { this.handleLogin()}}
                >
                  <LinearGradient
                    colors={['#08d4c4', '#01ab9d']}
                    style={styles.signIn}
                  >
                    <Text style={[styles.textSign, { color:'#fff' }]}>登录</Text>
                  </LinearGradient>
                </TouchableOpacity>

                <TouchableOpacity
                  onPress={() => this.props.navigation.navigate('Register')}
                  style={[styles.signIn, {
                    borderColor: '#009387',
                    borderWidth: 1,
                    marginTop: 15
                  }]}
                >
                  <Text style={[styles.textSign, { color: '#009387' }]}>注册</Text>
                </TouchableOpacity>
              </View>
            </ScrollView>

            <Text style={{textAlign: 'center', paddingVertical: 35}}>
              &copy;2020 版权所有 lagou.com
            </Text>
          </Animatable.View>
        </ImageBackground>
      </View>
    )
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1, 
    backgroundColor: '#009387'
  },
  header: {
    flex: 1,
    justifyContent: 'flex-end',
    paddingHorizontal: 20,
    paddingBottom: Platform.OS === 'ios' ? 150 : 100,
  },
  footer: {
    flex: 3,
    backgroundColor: '#fff',
    borderTopLeftRadius: 40,
    borderTopRightRadius: 40,
    paddingHorizontal: 20,
    paddingVertical: 30
  },
  textHeader: {
    color: '#fff',
    fontWeight: 'bold',
    fontSize: 30,
    textAlign: 'center'
  },
  textFooter: {
    color: '#05375a',
    fontSize: 18
  },
  action: {
    flexDirection: 'row',
    marginTop: 5,
    borderBottomWidth: 1,
    borderBottomColor: '#f2f2f2',
    paddingBottom: 5
  },
  actionError: {
    flexDirection: 'row',
    marginTop: 10,
    borderBottomWidth: 1,
    borderBottomColor: '#FF0000',
    paddingBottom: 5
  },
  textInput: {
    flex: 1,
    marginTop: Platform.OS === 'ios' ? 0 : -12,
    paddingLeft: 10,
    color: '#05375a',
  },
  errorMsg: {
    color: '#FF0000',
    fontSize: 14,
  },
  button: {
    alignItems: 'center',
    marginTop: 30
  },
  signIn: {
    width: '100%',
    height: 40,
    justifyContent: 'center',
    alignItems: 'center',
    borderRadius: 10
  },
  textSign: {
    fontSize: 18,
    fontWeight: 'bold'
  },
  image: {
    flex: 1,
    resizeMode: "cover",
    justifyContent: "center"
  },
});

export default connect(mapStateToProps, { login })(SignIn)